#！/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 2020-11-15 20:39:29
Author: wzh
Platform: Python 3.7.4 Windows-10-10.0.18362-SP0 AMD64
Email: hrcl2015@126.com
Wechat: hrcl2015(微信号)
Filename: down_chromedriver.py.py
Description : 根据当前系统chrome浏览器版本下载对应的chromedriver驱动
    
"""
import xml.etree.ElementTree as ET
import os,requests
from bs4 import BeautifulSoup
import zipfile,shutil
from fuzzywuzzy import fuzz,process

path0 = os.path.dirname(os.path.abspath(__file__)) + os.path.sep
driver_dir = os.path.join(path0, 'chromedriver') + os.path.sep
driver_zip_path = os.path.join(path0, 'zip') + os.path.sep
if not os.path.exists(driver_dir):os.makedirs(driver_dir)
if not os.path.exists(driver_zip_path):os.makedirs(driver_zip_path)

def get_chrome_version(chrome_dir=None,xml_fn=None):
    '''
    xml文件内容
    <Application xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
      <VisualElements
          ShowNameOnSquare150x150Logo='on'
          Square150x150Logo='86.0.4240.193\VisualElements\Logo.png'
          Square70x70Logo='86.0.4240.193\VisualElements\SmallLogo.png'
          Square44x44Logo='86.0.4240.193\VisualElements\SmallLogo.png'
          ForegroundText='light'
          BackgroundColor='#5F6368'/>
    </Application>
    '''
    fdir = chrome_dir if chrome_dir else 'C:/Program Files (x86)/Google/Chrome/Application/'
    fn = xml_fn if xml_fn else 'chrome.VisualElementsManifest.xml'
    if os.path.exists(fdir+fn):
        tree = ET.parse(fdir+fn)
        root = tree.getroot()
        ve=root[0]#VisualElements节点
        s=ve.attrib['Square150x150Logo']
        version_str=s.split('\\')[0]
        return version_str
def download_chromedriver(version_str):
    '''谷歌下载地址带参数
    http://chromedriver.storage.googleapis.com/86.0.4240.22/chromedriver_win32.zip?ich_args2=204-15215610038096_38455b0c983236d55506df5d8c407429_10001002_9c8a6429d3c7f9d7973d518939a83798_d9f8b6f31f629656a8042d0d6f64f3b5
    淘宝的镜像下载链接不用带参数
    https://cdn.npm.taobao.org/dist/chromedriver/86.0.4240.22/chromedriver_win32.zip
    清华镜像站没有链接
    '''
    version=version_str
    #版本号去掉最后一节，便于匹配最接近的版本  86.0.4240.193-->86.0.4240
    version_match=version.rsplit('.',maxsplit=1)[0]
    r=requests.get('http://npm.taobao.org/mirrors/chromedriver/')#获取列表哦
    txt=r.text
    soup=BeautifulSoup(txt,'lxml')
    version_lst=[x.text.replace('/','') for x in soup.findAll('a') if x.text.strip()]
    one = process.extractOne(version_match, version_lst,scorer=fuzz.UWRatio)
    version=one[0]#匹配到最近接的版本号
    print(f'浏览器{version_str}最接近的驱动版本号{version}')
    #http://npm.taobao.org/mirrors/chromedriver/
    url=f'http://npm.taobao.org/mirrors/chromedriver/{version}/chromedriver_win32.zip'
    #url=f'http://npm.taobao.org/dist/chromedriver/{version}/chromedriver_win32.zip'    
    file = requests.get(url)
    if file.status_code==200:
        fn=f"chromedriver_{version}.zip"
        with open(driver_zip_path+fn, 'wb') as zip_file: # 保存文件到指定目录
            zip_file.write(file.content)
            print(f'{driver_zip_path+fn}已保存')
        return fn
    else:
        print(f'status code:{file.status_code}')
    pass
def unpackfiles(zipname,unpack_dir=None,zipdir=''):
    '''解压zip打包文件，放到指定的目录下,如果未指定目录，则解到当前目录下的同名文件夹下
    unpack_dir:指定解压到目录（须含文件夹名）
    zipname:文件名
    zipdir:zip文件所在目录'''
    if unpack_dir is None:
        unpack_dir=zipname.split(sep='.')[0]
    zip_path=os.path.abspath(os.path.join(zipdir,zipname))
    if os.path.exists(zip_path):
        shutil.unpack_archive(zip_path,extract_dir=unpack_dir)
        print('unpacked to [%s]'%os.path.abspath(unpack_dir))
    else:
        print(zipname,' is not exist!')
    print('-'*20)
def unzip_file(zip_src, dst_dir):
    """解压zip文件
    zip_src:是zip文件的全路径
    dst_dir:解压目标文件夹(无压缩名文件夹)
    """
    r = zipfile.is_zipfile(zip_src)
    #print(zip_src)
    if r:
        fz = zipfile.ZipFile(zip_src, 'r')
        for file in fz.namelist():
            print('正在解压 %s'%file)
            fz.extract(file, dst_dir)
        print('%s 解压完成'%(zip_src))
        return True
    else:
        print('This is not zip files')
        return False
def unzip_chromedriver(zip_fn,version_str):
    '''解压chromedriver压缩文件到指定的位置，返回解压后的地址'''
    fn=zip_fn
    zip_fp=driver_zip_path+fn
    fdir=os.path.join(driver_dir,version_str) + os.path.sep#解压目录
    if not os.path.exists(fdir):os.makedirs(fdir)
    if unzip_file(zip_fp,fdir):
        return fdir+'chromedriver.exe'
    
if __name__=="__main__":
    chrome_version_str=get_chrome_version()
    zip_fn=download_chromedriver(chrome_version_str)
    driver_fp=unzip_chromedriver(zip_fn,chrome_version_str)
    pass

